package com.atbun.aclservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atbun.aclservice.entity.AclRole;
import com.atbun.aclservice.entity.AclUser;
import com.atbun.aclservice.service.IndexService;
import com.atbun.aclservice.service.PermissionService;
import com.atbun.aclservice.service.RoleService;
import com.atbun.aclservice.service.UserService;
import com.atbun.servicebase.exceptionHandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description :
 * @Author : mayp
 * @Date: 2020-05-24 16:39
 */
@Service
public class IndexServiceImpl implements IndexService {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据用户名获取登录信息
     */
    @Override
    public Map<String, Object> getUserInfo(String username) {
        Map<String, Object> result = new HashMap<>();

//        根据用户名查找用户信息
        AclUser aclUser = userService.selectByUsername(username);
        if (null == aclUser){
            throw new GuliException(20001,"该用户不存在");
        }
//        根据用户id获取角色
        Map<String, Object> roleMap = roleService.findRoleByUserId(aclUser.getId());
        List<AclRole> roleList = (List<AclRole>) roleMap.get("assignRoles");
//        得到该用户下的所有角色名称
        List<String> roleNameList = roleList.stream().map(item -> item.getRoleName()).collect(Collectors.toList());
        if (roleNameList.size() == 0) {
//              前端框架必须返回一个角色，否则报错，如果没有角色，返回一个空角色
            roleNameList.add("");
        }
//        根据用户id查询权限
        List<String> permissionValueList = permissionService.selectPermissionValueByUserId(aclUser.getId());
//        放入redis中
        redisTemplate.opsForValue().set(username,permissionValueList);

        result.put("name", aclUser.getUsername()); // 用户名称
        result.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif"); //默认头像
        result.put("roles", roleNameList); //用户角色集合
        result.put("permissionValueList", permissionValueList); // 用户权限
        return result;
    }

    /**
     * 根据用户名获取动态菜单
     * @param username
     * @return
     */
    @Override
    public List<JSONObject> getMenu(String username) {
//        根据用户名查找用户信息
        AclUser aclUser = userService.selectByUsername(username);
//        根据用户id获取菜单权限
        List<JSONObject> permissionList = permissionService.selectPermissionByUserId(aclUser.getId());
        return permissionList;
    }
}
